package ru.aptu.gsp_banking.service_impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.aptu.gsp_banking.dao.CardDAO;
import ru.aptu.gsp_banking.domain.Card;
import ru.aptu.gsp_banking.service.CardService;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 11/18/11
 * Time: 1:32 AM
 */

@Service
public class CardServiceImpl implements CardService {

    @Autowired
    private CardDAO cardDAO;

    @Transactional
    public List<Card> listCard(Integer accountId) {
        return cardDAO.listCard(accountId);
    }

    @Transactional
    public void removeCard(Integer id) {
        cardDAO.removeCard(id);
    }

    @Transactional
    public void addCard(Card card) {
        cardDAO.addCard(card);
    }

    @Transactional
    public void updateCard(Card card) {
        cardDAO.updateCard(card);
    }

    @Transactional
    public Card getCard(Integer cardId) {
        return cardDAO.getCard(cardId);
    }

    @Transactional
    public boolean checkCard(Integer cardId, String name) {
        return cardDAO.checkCard(cardId, name);
    }

    @Transactional
    public String getFreeCardNumber() {
        String lastCardNumberStr = cardDAO.getLastCardNumber();
        lastCardNumberStr = lastCardNumberStr.replaceAll(" ", "");
        Long lastCardNumberInt = Long.parseLong(lastCardNumberStr);
        ++lastCardNumberInt;

        StringBuilder freeCardNumber = new StringBuilder(lastCardNumberInt.toString());
        freeCardNumber.insert(4, ' ');
        freeCardNumber.insert(9, ' ');
        freeCardNumber.insert(14, ' ');
        String freeCardNumberStr = freeCardNumber.toString();

        return freeCardNumberStr;
    }
}
